<template>
  <view class="snowy-page">
    <view class="snowy-flex-vh-center logo-content" @tap="logoTap">
      <image class="logo" :alt="sysBaseConfig.SNOWY_SYS_NAME" :src="sysBaseConfig.SNOWY_SYS_LOGO" mode="scaleToFill">
      </image>
      <text class="title">{{sysBaseConfig.SNOWY_SYS_NAME}} {{sysBaseConfig.SNOWY_SYS_VERSION}}</text>
    </view>
    <view class="login-form">
      <view class="snowy-shadow snowy-flex-v-center input-item" v-if="curEnv.loginSwitchTenant && tenanData.length > 0">
        <uni-icons class="icon" type="home-filled" size="20" color="#5677fc"></uni-icons>
        <picker class="input" :value="curTenanIndex" :range="tenanData" range-key="name" @change="tenanChange">
          <view class="uni-input">{{tenanData[curTenanIndex].name}}</view>
        </picker>
      </view>
      <view class="snowy-shadow snowy-flex-v-center input-item">
        <uni-icons class="icon" type="person-filled" size="20" color="#5677fc"></uni-icons>
        <input v-model="loginForm.account" class="input" type="text" placeholder="请输入账号" maxlength="30" />
      </view>
      <view class="snowy-shadow snowy-flex-v-center input-item">
        <uni-icons class="icon" type="locked-filled" size="20" color="#5677fc"></uni-icons>
        <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
      </view>
      <view class="snowy-shadow snowy-flex-v-center input-item" v-if="sysBaseConfig.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN === 'true'">
        <uni-icons class="icon" type="map-filled" size="20" color="#5677fc"></uni-icons>
        <input v-model="loginForm.validCode" type="text" class="input" placeholder="请输入验证码" maxlength="4" />
        <image :src="validCodeBase64" @click="loginCaptcha" class="login-code-img" mode="scaleToFill"></image>
      </view>
      <view>
        <tui-button margin="70rpx 0" :preventClick="true" :shadow="true" @click="handleLogin">登录</tui-button>
      </view>
      <view class="register-link">
        <text class="link" @click="scnuSSOLogin">还没有账号？立即注册</text>
      </view>

      <view class="divider">
        <view class="line"></view>
        <text class="text">其他登录方式</text>
        <view class="line"></view>
      </view>

      <view class="other-login">

        <!--        <view class="wechat-login">-->
        <!--          <button class="wechat-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">-->
        <!--            <uni-icons type="weixin" size="40" color="#07c160"></uni-icons>-->
        <!--          </button>-->
        <!--        </view>-->

        <view class="university-login">
          <button class="university-btn" @click="scnuSSOLogin">
            华南师范大学统一认证登录
          </button>
        </view>
        <!--        <view class="university-login">-->
        <!--          <button class="university-btn" @click="scnuSSOWeChatRegister">-->
        <!--            统一认证注册-->
        <!--          </button>-->
        <!--        </view>-->
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, reactive, getCurrentInstance, computed } from 'vue'
import loginApi from '@/api/auth/login-api'
import tenApi from '@/api/ten/ten-api'
import store from '@/store'
import config from '@/config'

const encryptedData = ref('')
const iv = ref('')
const phone = ref('')
const sessionId = ref('')
const { proxy } = getCurrentInstance()
// 当前租户index
const curTenanIndex = ref(0)
// 所有租户
const tenanData = ref([])
// 验证码
const validCodeBase64 = ref("")
// 登录表单
const loginForm = ref({
  // account: 'superAdmin',
  // password: '123456',
  account: '',
  password: '',
  validCode: '',
  validCodeReqNo: '',
  phone: ''
})
// 跳转到注册页面
const goToRegister = () => {
  uni.$snowy.tab.navigateTo('/pages/auth/register')
}

store.dispatch('GetSysBaseConfig')
// 系统配置
const sysBaseConfig = computed(() => {
  return store.getters.sysBaseConfig
})
// 当前环境
const curEnv = computed(() => {
  return store.getters.curEnv
})
// 点击logo
const logoTap = () => {
  if (!config.ENABLE_CONFIG_PAGE) { return }
  uni.$snowy.tab.navigateTo('/pages/config/index')
}
// 获取租户
const getTenSelector = async () => {
  if (!curEnv.value?.loginSwitchTenant) {
    return
  }
  const data = await tenApi.tenSelector()
  tenanData.value = [{
    name: '主租户',
    domain: curEnv.value.mainTenantDomain
  }].concat(data)
  const indexOfRes = uni.$xeu.findIndexOf(tenanData.value, item => item.domain === store.getters.tenantDomain)
  if (indexOfRes) {
    curTenanIndex.value = indexOfRes
  }
}
if(config.IS_ENTTERPRISE){
  getTenSelector()
}
// 租户切换
const tenanChange = (e) => {
  curTenanIndex.value = e.detail.value;
  store.commit('SET_tenantDomain', tenanData.value[curTenanIndex.value]?.domain)
  // 切换租户后重新获取配置文件和验证码
  store.dispatch('GetSysBaseConfig')
  if (sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN) {
    loginCaptcha()
  }
}

// 获取图形验证码
const loginCaptcha = async () => {
  const data = await loginApi.getPicCaptcha()
  validCodeBase64.value = data?.validCodeBase64
  loginForm.value.validCodeReqNo = data?.validCodeReqNo
}
if (sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN) {
  loginCaptcha()
}

// 登录方法
const handleLogin = () => {
  if (loginForm.value.account === "") {
    uni.$snowy.modal.msgError("请输入账号")
  } else if (loginForm.value.password === "") {
    uni.$snowy.modal.msgError("请输入密码")
  } else if (loginForm.value.validCode === "" && sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN === 'true') {
    uni.$snowy.modal.msgError("请输入验证码")
  } else {
    pwdLogin()
  }
}
// 密码登录
const pwdLogin = () => {
  store.dispatch('Login', loginForm.value).then(() => {
    // 所有异步请求结束之后才能够进行下一步操作
    Promise.all([
      store.dispatch('GetUserLoginMenu'),
      store.dispatch('GetUserInfo'),
      store.dispatch('GetDictTypeTreeData'),
    ]).then((result) => {
      // #ifdef H5
      const { searchQuery, hashQuery } = uni.$xeu.parseUrl(location.href)
      if (searchQuery.redirect) {
        uni.$snowy.tab.reLaunch(searchQuery.redirect)
      } else if (hashQuery.redirect) {
        uni.$snowy.tab.reLaunch(hashQuery.redirect)
      } else {
        // #endif
        uni.$snowy.tab.reLaunch('/pages/home/index')
        // #ifdef H5
      }
      // #endif
    }).catch(err => {
      if (sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN) {
        loginCaptcha()
        loginForm.value.validCode = ""
      }
    })
  }).catch(err => {
    if (sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN) {
      loginCaptcha()
      loginForm.value.validCode = ""
    }
  })
}

// 华南师范大学统一认证登录
const scnuSSOLogin = () => {
  uni.showLoading({ title: '统一认证登录中...', mask: true });

  uni.login({
    provider: 'weixin',
    success: (wxRes) => {
      uni.hideLoading();
      if (wxRes.code) {
        uni.navigateTo({
          url: `/pages/auth/sso?wxCode=${wxRes.code}`
        });
      } else {
        uni.$snowy.modal.msgError('获取微信授权失败');
      }
    },
    fail: (err) => {
      uni.hideLoading();
      uni.$snowy.modal.msgError('微信登录失败，请重试');
    }
  })
}

// SCNUSSO注册小程序
const scnuSSOWeChatRegister = async () => {
  uni.showLoading({
    title: '统一认证注册中...',
    mask: true
  });

  const res = await loginApi.scnuSSOWeChatResgister();

  uni.hideLoading();

  if(res.data === true) {
    uni.showToast({
      title: '统一认证注册成功',
      icon: 'success'
    })
    return true
  } else {
    uni.showToast({
      title: res.message || '统一认证注册失败，请重试',
      icon: 'none'
    })
    return false
  }
}

// 微信登录
const getPhoneNumber = async (e) => {
  let res = await new loginApi.AuthPhone(e.detail.code)
  console.log(res)
  loginForm.value.phone = res.phoneNumber// 获取到手机号
  //将用户的信息发送给后台，后台根据用户的信息判断用户是否是新用户
  store.dispatch('WxLogin', loginForm.value).then(() => {
    // 所有异步请求结束之后才能够进行下一步操作
    Promise.all([
      store.dispatch('GetUserLoginMenu'),
      store.dispatch('GetUserInfo'),
      store.dispatch('GetDictTypeTreeData'),
    ]).then((result) => {
      // #ifdef H5
      const { searchQuery, hashQuery } = uni.$xeu.parseUrl(location.href)
      if (searchQuery.redirect) {
        uni.$snowy.tab.reLaunch(searchQuery.redirect)
      } else if (hashQuery.redirect) {
        uni.$snowy.tab.reLaunch(hashQuery.redirect)
      } else {
        // #endif
        uni.$snowy.tab.reLaunch('/pages/home/index')
        // #ifdef H5
      }
      // #endif
    }).catch(err => {
      if (sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN) {
        loginCaptcha()
        loginForm.value.validCode = ""
      }
    })
  }).catch(err => {
    if (sysBaseConfig.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN) {
      loginCaptcha()
      loginForm.value.validCode = ""
    }
  })
}

const handleWechatLogin = ()=>{
  uni.getUserProfile({
    desc: '用于完善用户资料',
    success:(userProfile) =>{
      console.log("查看userProfile")
      console.log(userProfile)
      encryptedData.value = userProfile.encryptedData
      iv.value = userProfile.iv
      uni.login({
        provider: 'weixin',
        success: async function(res) {
          loginApi.wxlogin({code:res.code,encryptedData:encryptedData.value,iv:iv.value}).then(data => {
            // 将获取到的数据传给后台，后台来进行解密获取到用户信息
            console.log(data)
          }).catch(error => {
            console.log("后台接口调用失败")
          })
        },
        fail: function() {
          uni.$snowy.modal.msgError('微信登录失败')
        }
      })
    },
    fail:(err) =>{
      uni.$snowy.modal.msgError('用户拒绝授权')
    }
  })

  // #ifdef H5
  uni.$snowy.modal.msgError('H5环境暂不支持微信登录')
  // #endif
}
</script>
<style lang="scss" scoped>
page {
  background-color: #ffffff;
}

.logo-content {
  margin: 15% auto;

  .logo {
    width: 100rpx;
    height: 100rpx;
  }

  .title {
    font-size: 40rpx;
    margin-left: 15rpx;
  }
}

.login-form {
  margin: 60rpx auto;
  width: 80%;

  .input-item {
    margin: 35rpx auto;
    background-color: #f5f6f7;
    height: 90rpx;

    .icon {
      margin-left: 20rpx;
    }

    .input {
      width: 100%;
      font-size: 30rpx;
      padding-left: 25rpx;
    }

    .login-code-img {
      cursor: pointer;
      width: 70%;
      height: 85rpx
    }
  }
}
.divider {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;

  .line {
    flex: 1;
    height: 1px;
    background-color: #e5e5e5;
  }

  .text {
    color: #999;
    padding: 0 30rpx;
    font-size: 24rpx;
  }
}

.other-login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20rpx;

  .wechat-login {
    display: flex;
    flex-direction: column;
    align-items: center;

    .login-text {
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #07c160;
    }
  }
  
  .university-login {
    width: 100%;
    
    .university-btn {
      width: 100%;
      background: linear-gradient(135deg, #d73a49, #e53e3e);
      color: white;
      border: none;
      border-radius: 8rpx;
      padding: 24rpx 0;
      font-size: 32rpx;
      font-weight: 500;
      box-shadow: 0 4rpx 12rpx rgba(215, 58, 73, 0.3);
      transition: all 0.3s;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 2rpx 8rpx rgba(215, 58, 73, 0.4);
      }
    }
  }
}
.register-link {
  text-align: center;
  margin-bottom: 30rpx;

  .link {
    font-size: 28rpx;
    color: #5677fc;
    cursor: pointer;
  }
}
</style>